<template>
  <!--新增/编辑跟进-->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      :title="title2"
      :beforeClose="handleClose2"
      :visible.sync="dialogVisible2"
      width="1100px">
      <el-form v-loading="loading2" :model="trackingForm" size="mini" label-width="110px" :rules="rules" ref="trackingForm">
        <el-row>
          <el-col :span="8">
            <el-form-item label="供应商名称：" >
              {{trackingForm.customerName}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供应商类型：" >
              {{supplierType}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系人：" prop="contactId">
              <el-select  v-model="trackingForm.contactId"  placeholder="请选择联系人" style="width:150px;">
                <el-option v-for="item in supplierContactList" :key="item.contactId" :label="item.contactName" :value="item.contactId"></el-option>
              </el-select>
              <el-button type="text" style="margin-left:10px" v-if="popType == 'add'" @click="showAddContact('add',trackingForm.supplierId)">新增</el-button>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row>

          <el-col :span="8">
            <el-form-item label="跟进方式：" prop="followUpId">
              <el-select  v-model="trackingForm.followUpId" placeholder="请选择" clearable @change="changeTmId">
                <el-option v-for="item in trackingMethodList"  :value="item.tmId" :disabled="item.disabled" :label="item.trackingMethod" :key="item.trackingMethod"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="跟进目的：" prop="trackingPurposeValue">
              <el-input v-model="trackingForm.trackingPurposeValue"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="目的是否完成：" prop="isInvalid">
              <el-radio-group v-model="trackingForm.isInvalid">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="supplierType == '聚合工厂'">
           <el-col :span="8">
             <el-form-item label="当前库存：" prop="currentStock"><el-input v-model="trackingForm.currentStock"></el-input></el-form-item>
           </el-col>
          <el-col :span="8">
            <el-form-item label="每天产能：" prop="dayCapacity"><el-input v-model="trackingForm.dayCapacity"></el-input></el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="当天卖货量：" prop="todayOrderNum"><el-input v-model="trackingForm.todayOrderNum"></el-input></el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="跟进内容：" prop="trackingContent">
          <el-input v-model="trackingForm.trackingContent" :autosize="{ minRows: 2, maxRows: 6}" type="textarea" :rows="2"></el-input>
        </el-form-item>



        <el-form-item label="附件：" >
          <div v-if="trackingForm.followUpId==2">
            <div
              style="width:90px;height:120px;margin-bottom:10px;margin-right:10px;vertical-align: middle;position: relative;display:inline-block"
              v-for="(item,index) in trackingForm.trackingPics"
              :key="index">
              <el-image
                style="width:100%;height:100%;object-fit:contain;"
                :src="item"
                :preview-src-list="Array(item)">
              </el-image>
            </div>
          </div>
          <div v-else>
            <div v-if="trackingForm.trackingPics.length>0">
              <div v-for="(item,index) in trackingForm.trackingPics" :key="index" style="margin-bottom: 10px;">
                <div v-if="item!=''">
                  <el-input :value="item" readonly style="width: 500px;"></el-input>
                  <i class="el-icon-delete-solid" style="cursor: pointer;color:red;font-size:18px;" @click="delImg(index)"></i>
                </div>
              </div>
            </div>
            <el-upload
              v-if="trackingForm.trackingPics.length<9"
              action="https://upload.qiniup.com"
              drag
              :data="uploadToken"
              :show-file-list="false"
              :http-request="function (upload) { return sliderRequest(upload) }">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em><br/></div>
            </el-upload>
          </div>


        </el-form-item>
        <el-form-item label="下次跟进时间：">
          <el-date-picker
            v-model="trackingForm.nextTrackingTime"
            align="right"
            type="date"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
<!--        <el-form-item label="备注：">-->
<!--          <el-input v-model="trackingForm.trackingRemark"  :autosize="{ minRows: 2, maxRows: 6}" type="textarea" :rows="2"></el-input>-->
<!--        </el-form-item>-->
      </el-form>
      <span slot="footer" class="dialog-footer" v-if="this.popType!='see'">
        <el-button @click="handleClose2">取 消</el-button>
        <el-button type="primary" @click="handleConfirm2" :loading="btnLoading2">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 新增联系人 -->
    <addSupplierContact ref="addSupplierContact" @update="getSupplierContactList"></addSupplierContact>
  </div>

</template>
<script>
import axios from 'axios'
import { getQiniuToken } from '@/api/partner'
import {
  addSupplierTrackingAPI,
  customerStepList,
  customerStepDetail,
  supplierContactList,
} from '@/api/company'
import {
  supplierPurposeListAPI,
  getTrackingMethodListAPI2,
  trackingInteractListAPI
} from "@/api/fms.js";
import {validatePhone} from '@/utils/validate';
import {formatDate} from '@/utils/date';
import jt from '@/assets/images/jt.png';
import addSupplierContact from './addSupplierContact.vue';
// import gjzy from './gjzy'
import store from '@/store'
import { mapGetters } from 'vuex'

const defaultTrackingForm = {
  trackingId:'',
  supplierId:'',
  contactId:'',
  followUpId:'',
  followUpValue:'',
  trackingContent:'',
  trackingPics:[],
  nextTrackingTime:'',
  trackingRemark:'',
  isInvalid:null,
  stepId:'',
  stepName:'',
  trackingMethodId:'',
  trackingMethodValue:'',
  trackingPurposeId:'',
  trackingPurposeValue:'',
  customerName:'',
  currentStock:'',
  dayCapacity:'',
  todayOrderNum:''
};

export default {
  name: "addSupplierGj",
  data(){
    return {
      loading2:false,
      dialogVisible2:false,
      title2:'',
      btnLoading2:false,
      trackingForm: JSON.parse(JSON.stringify(defaultTrackingForm)),
      listQueryContact: {
        supplierId:'',
        pageNum: 1,
        pageSize: 100,
      },
      supplierContactList:[],//联系人列表
      rules:{
        contactId:[{required: true, message: '请选择联系人', trigger: 'change'},],
        followUpId:[{required: true, message: '请选择跟进方式', trigger: 'change'},],
        trackingMethodId:[{required: true, message: '请选择沟通方式', trigger: 'change'},],
        trackingPurposeValue:[{required: true, message: '请输入跟进目的', trigger: 'blur'},],
        trackingContent:[{required: true, message: '请填写跟进内容', trigger: 'blur'},],
        isInvalid:[{required: true, message: '请选择目的是否完成', trigger: 'change'},],
        currentStock:[{required: true, message: '此项必填', trigger: 'blur'},],
        dayCapacity:[{required: true, message: '此项必填', trigger: 'blur'},],
        todayOrderNum:[{required: true, message: '此项必填', trigger: 'blur'},],
      },
      uploadToken:{
        token:'',
      },
      imgDomain: '',
      fileLoading:false,
      popType:'',
      // isBuyPermission:-1,
      // goodsMatchDegreeList:[],
      trackingMethodList:[],
      interactList:[],
      purposeList:[],
      stepList:[],
      jt:jt,
      stepName:'',
      introduce:'',
      // followType:'',
      dataId:'',
      topStepList:[],
      allTracking :'',
      allVisit :'',
      tackingNum :'',
      visitNum :'',
      topPurposeList :[],
      stepId:'',
      supplierType:''
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId'
    ]),
  },
  components: {
    addSupplierContact,
    // gjzy,
  },
  created() {


  },
  filters: {

  },
  methods: {
      //上传文件重写
    sliderRequest(upload) {
      // 文件上传自行处理上传
      // 创建FormData对象 添加相关上传参数
      const formData = new FormData()
      // 文件对象
      formData.append('file', upload.file)
      // key 文件名处理，这样的话七牛会识别文件时什么类型
      let timestamp = new Date().getTime();
      let fileName = timestamp + upload.file.name
      formData.append('key', fileName)
      formData.append('token', this.uploadToken.token)
      // 上传文件
      axios.post("https://upload.qiniup.com", formData, {
        onUploadProgress: (event) => {
          // 监听上传进度
          this.fileLoading = true;
          event.percent = event.loaded / event.total * 100
          upload.onProgress(event)
        }
      }).then((response) => {
        if (response.status === 200) {
          let res = response.data;
          this.trackingForm.trackingPics.push(this.imgDomain + res.key)
          this.fileLoading = false;
        } else {
          this.fileLoading = false;
          this.handleAvatarError2()
        }
      }).catch((err) => {
        this.fileLoading = false;
        this.handleAvatarError2()
      })
    },
    handleAvatarError2() {
      this.$message({
        message: '上传失败',
        type: 'error'
      });
    },
    //获取客户阶段
    // getCustomerStepList(){
    //   return customerStepList({dataId:this.dataId}).then((res)=>{
    //     this.topStepList = res
    //   })
    // },
    //切换跟进方式，变化沟通方式
    changeTmId(){
      this.interactList = [];
      this.trackingForm.trackingMethodId = ''
      if(this.trackingForm.followUpId){
        this.getInteractList();
      }
    },
    //切换跟进目的，变化目的说明
    changePurposeId() {
      let i = this.purposeList.findIndex((el)=>{
        return el.purposeId == this.trackingForm.trackingPurposeId;
      })
      if(i!= -1){
        this.introduce = this.purposeList[i]['introduce'];
      } else if (this.trackingForm.trackingPurposeId == -1) {
        this.introduce = '公司破产或已关闭';
      }
    },
    //跟进目的列表
    getPurposeList(){
      supplierPurposeListAPI({supplierId:this.trackingForm.supplierId}).then((res) => {
        this.purposeList = res.list;
      })
    },

    //跟进方式
    getTrackingMethodList(){
      getTrackingMethodListAPI2({pageNum:1,pageSize: 1000,isEnable:1}).then((res)=>{
        this.trackingMethodList = res.list
        this.trackingMethodList.forEach((item) => {
          if (item.tmId == 2) {
            item.disabled = true;
          }
        })
      })
    },

    //沟通方式
    getInteractList(){
      trackingInteractListAPI({
        pageNum: 1,
        pageSize: 1000,
        isEnable: 1,
        tmId: this.trackingForm.followUpId
      }).then((res) => {
        this.interactList = res.list
      })
    },

    //显示增加联系人
    showAddContact(type, item) {
      if (type == 'add') {
        this.$refs.addSupplierContact.showPop(type,item)
      }
    },

    //获取七牛TOKEN
    getUploadToken(){
      getQiniuToken().then((res)=>{
        this.uploadToken.token = res.token;
        this.imgDomain = res.domain
      })
    },
    //上传图片
    handleAvatarSuccess(res){
      this.trackingForm.trackingPics.push(this.imgDomain+res.key)
    },

    //删除图片
    delImg(index){
      this.trackingForm.trackingPics.splice(index,1)
    },

    //显示新增/编辑跟进
    showPop(type, item) {
      this.dialogVisible2 = true;
      this.loading2 = true;
      this.popType = type;
      this.trackingForm = JSON.parse(JSON.stringify(defaultTrackingForm));
      this.introduce = '';
      this.listQueryContact.supplierId = this.trackingForm.supplierId = item.supplierId;
      this.getUploadToken();
      Promise.all([
        this.getSupplierContactList(),
        this.getPurposeList(),
        this.getTrackingMethodList(),
      ]).then(() => {
        this.loading2 = false;
        if (type == 'add') {
          this.title2 = '新增跟进';
          this.trackingForm.customerName = item.supplierName ? item.supplierName : item.customerName;
          this.trackingForm.contactId = this.supplierContactList[0] ? this.supplierContactList[0].contactId : '';
        } else if (type == 'edit'||type == 'see') {
          this.title2 = type == 'edit' ? '编辑跟进' : '查看跟进';
          for(let key in defaultTrackingForm){
            this.trackingForm[key] = item[key] ? item[key] : defaultTrackingForm[key];
          }
          this.trackingForm.isInvalid = Number(item.isInvalid);
          this.changePurposeId();
          this.getInteractList();
        }
      }).catch(() => { this.loading2 = false; })

    //显示跟进阶段指引
    // showGj(item){
    //   this.$refs.gjzy.showPop(item.stepId,this.followType,this.dataId,item.type)
    // },
    //画图
    // draw(x,y,y2){
    //   document.getElementById('main').removeAttribute('_echarts_instance_')
    //   var chartDom = document.getElementById('main');
    //   var myChart = this.$echarts.init(chartDom);
    //   var option;
    //   let self = this;
    //   var txt1 = "预计" + self.allTracking + self.allVisit + '次拜访' + ' '+'已完成'+self.tackingNum + '次日常跟进，'+self.visitNum + '次拜访'
    //   let time = new Date(new Date().toLocaleDateString()).getTime()
    //   let length = x.length-1
    //   option = {
    //     title: {
    //       text: txt1,
    //       left: '4%',
    //       top: '0',
    //       textStyle:{
    //         fontSize:12
    //       }
    //     },
    //     grid: {
    //       left: '3%',
    //       top: '30%',
    //       right:'5%'
    //     },
    //     xAxis: {
    //       data:x,
    //       axisLine:{
    //         lineStyle: {
    //           color:'#999'
    //         },
    //       },
    //       axisLabel: {
    //         color:'#000',
    //         showMaxLabel:true,
    //         formatter: function (value, index) {
    //           var txt = "当前进度"
    //           if(value*1000 == time){
    //             return "{jt|}\n" + txt
    //           }else if(index == 0 || index == length) {
    //             // console.log("index",index)
    //             return `{a|${formatDate(new Date(value * 1000), 'MM-dd')}}`
    //           }
    //         },
    //         rich: {
    //           a: {
    //             color: '#000',
    //             fontSize: '8px',
    //           },
    //           jt: {
    //             height: 20,
    //             align: 'center',
    //             fontSize: '8px',
    //             backgroundColor: {
    //               image: self.jt
    //             }
    //           },
    //         },
    //       },
    //     },
    //     yAxis: {
    //       axisLine:{
    //         show:true,
    //         lineStyle: {
    //           color:'#999'
    //         },
    //       },
    //       axisTick:{
    //         show:false
    //       },
    //       axisLabel: {
    //         show:false
    //       },
    //       splitLine:{
    //         show:false
    //       },
    //     },
    //     series: [
    //       {
    //         name: '拜访',
    //         data: y2,
    //         type: 'scatter',
    //         emphasis: {
    //           focus: 'series',
    //         },
    //         symbol:'rect',
    //         itemStyle: {
    //           color: new this.$echarts.graphic.RadialGradient(0.4, 0.3, 1, [
    //             {
    //               offset: 0,
    //               color: 'rgb(251, 118, 123)'
    //             },
    //             {
    //               offset: 1,
    //               color: 'rgb(204, 46, 72)'
    //             }
    //           ])
    //         }
    //       },
    //       {
    //         name: '日常跟进',
    //         data: y,
    //         type: 'scatter',
    //         emphasis: {
    //           focus: 'series',
    //         },
    //         itemStyle: {
    //           color: new this.$echarts.graphic.RadialGradient(0.4, 0.3, 1, [
    //             {
    //               offset: 0,
    //               color: 'rgb(129, 227, 238)'
    //             },
    //             {
    //               offset: 1,
    //               color: 'rgb(25, 183, 207)'
    //             }
    //           ])
    //         }
    //       }
    //     ]
    //   };
    //   option && myChart.setOption(option);
    // },

      // 客户跟进阶段
      // this.getCustomerStepList().then(()=>{
      //   let i = this.topStepList.findIndex((el)=>{
      //     return el.type == 3
      //   })
      //   if(i!=-1){
      //     this.stepId = this.topStepList[i]['stepId']
      //     customerStepDetail({dataId:this.dataId,stepId:this.topStepList[i]['stepId']}).then((res)=>{
      //       this.allTracking = res.allTracking;
      //       this.allVisit = res.allVisit;
      //       this.tackingNum = res.tackingNum;
      //       this.visitNum = res.visitNum;
      //       this.topPurposeList = res.purposeList;
      //       this.$nextTick(()=>{
      //         this.draw(res.x,res.y,res.y2)
      //       })
      //     })
      //   }
      // });
    },

    //关闭跟进弹窗
    handleClose2(){
      this.$refs.trackingForm.resetFields();
      this.dialogVisible2 = false;
      this.btnLoading2 = false;
    },

    //提交跟进
    handleConfirm2(){
      this.$refs.trackingForm.validate((valid) => {
        if (valid) {
          this.btnLoading2 = true;
          let data = JSON.parse(JSON.stringify(this.trackingForm));
          data.trackingPics = data.trackingPics.join(",");
          //跟进方式
          let ti = this.trackingMethodList.findIndex((el)=>{
            return el.tmId == data.followUpId;
          })
          data.followUpValue =  this.trackingMethodList[ti]['trackingMethod']
          //沟通方式
          let mi = this.interactList.findIndex((el)=>{
            return el.interactId == data.trackingMethodId;
          })
          if(mi != -1){
            data.trackingMethodValue = this.interactList[mi]['interactType']
          }

          // 跟进目的
          // if (data.trackingPurposeId != -1) {
          //   let pi = this.purposeList.findIndex((el)=>{
          //     return el.purposeId == data.trackingPurposeId;
          //   })
          //   data.trackingPurposeValue =  this.purposeList[pi]['purposeTitle']
          // }else{
          //   data.trackingPurposeValue = '公司破产或已关闭'
          // }
          addSupplierTrackingAPI(data).then((res)=>{
            this.btnLoading2 = false;
            this.handleClose2();
            this.$emit('update');
            this.$message.success('操作成功!')
          }).catch(()=>{
            this.btnLoading2 = false;
          })
        }
      })
    },

    // 获取供应商组织人员列表
    getSupplierContactList() {
      return supplierContactList(this.listQueryContact).then((res) => {
        this.supplierContactList = res.list;
        this.supplierType = res.supplierType
      })
    },
  },
}
</script>

<style  lang="scss">
.step-div{
  border-radius: 8px;
  margin-bottom:40px;
  background: #f5f7fa;
  padding:0 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .step-div-list{
    display: flex;
    align-items: center;
    justify-content: flex-start;
  }
  .step-item{
    display: flex;
    align-items: center;
    justify-content: flex-start;
    height:110px;
  }
  .step-item-name{
    padding:0 20px;
    color:#c0c4cc;
    position: relative;
    text-align: center;
    line-height: 20px;
    cursor: pointer;
    font-size:12px;
    white-space:nowrap;
  }
  .step-item-info{
    background: #fff;
    border-radius: 10px;
    padding:10px;
    width:660px;
    height:100px;
    margin-right:10px;
    .info-row{
      display: flex;
      justify-content: flex-start;
      align-items: center;
      height:50%;
      .info-name{
        font-size:12px;
        width:70px;
      }
      .info-div{
        flex:1
      }
    }
  }

}
.chceckspan{
  max-width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding-right: 20px;
  box-sizing: border-box;
  margin:5px;
  cursor: default;
  .el-tag__close{
    float: right;
    margin-top: -17px;
    margin-right: -15px;
  }
}
.chceckspan.chceckspan2 .el-tag__close{
  margin-top: 0;
}
.avatar-uploader{
  margin-bottom:10px;
  display: inline-block;
  width:80px;
  height:80px;
  border:1px solid #DCDFE6;
  text-align: center;
  line-height: 80px;
  vertical-align: middle;
}
.check-item{
  overflow: hidden;
  margin-bottom:5px;
  .el-checkbox{
    float:left;
    line-height: 20px;
  }
  .el-checkbox__label{
    display: none;
  }
  .label{
    float:left;
    width:calc(100% - 30px);
    margin-left:10px;
    line-height: 20px;
    font-size: 12px;
  }
}
.target-div{
  height:24px;
  width:100%;
  position: relative;
  .target-line{
    position: absolute;
    width:100%;
    height:2px;
    background: #dcdfe6;
    top:50%;
    margin-top:-1px;
    z-index: 0;
  }
  .target-list{
    width:100%;
    height:24px;
    display: flex;
    justify-content:space-between;
    align-items: center;
    z-index: 1;
    position: relative;
    .target-item{
      width:24px;
      height:24px;
      border-radius: 50%;
      background: rgb(192,196,204);
      text-align: center;
      line-height: 24px;
      color:#fff;
      font-size: 12px;
    }
  }
}
</style>
